package com.wulwu.permission.filter;

import com.wulwu.permission.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Description 登录成功后 走此类进行鉴权操作
 * @Author Major
 * @Date 2020/12/4 17:05
 */
public class JWTValidationFilter extends BasicAuthenticationFilter {

    public JWTValidationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(setAuthtication(request.getHeader(JwtUtils.TOKEN_HEADER)));
        super.doFilterInternal(request, response, chain);
    }

    private UsernamePasswordAuthenticationToken setAuthtication(String token) {
        if (StringUtils.isNotBlank(token)) {
            String jwtToken = token.replace(JwtUtils.TOKEN_PREFIX, "");
            String username = JwtUtils.getUsername(jwtToken);
            if (StringUtils.isNotBlank(username)) {
                boolean expiration = JwtUtils.isExpiration(jwtToken);
                if (!expiration){
                    return null;
                }
                List<SimpleGrantedAuthority> grantedAuthorities = JwtUtils.getPermission(jwtToken);
                //根据 token 重新授权，实现 集群部署的效果
                return new UsernamePasswordAuthenticationToken(username, null, grantedAuthorities);
            }
        }
        return null;
    }
}
